; NAME:
; Convert_To_MoleculesCm2Sec
; 
; PURPOSE:
; Converts from given units to molecules/cm/s
; 
; CATEGORY:
; Regrid
; 
; CALLING SEQUENCE:
; Convert_To_MoleculesCm2Sec, InData, OutData, Units
; 
; INPUTS:
; InData =  Input data
; Units = Units given in a string
; 
; OUTPUTS:
; OutData = Converted data
; 
; SIDE EFFECTS:
;
; RESTRICTIONS:
;
; PROCEDURE:
;
; MODIFICATION HISTORY:
;   Written Feb 14, 2014 by as13988

PRO Convert_To_MoleculesCm2Sec, InData, OutData, Units, SPECIES = Species

  ; Check that the units are a string
  if size(Units, /Type) ne 7 then begin
    Print, 'Units were not given as a string'
    Print, 'No units conversion done'
    OutData = InData
    Return
    
  endif
  
  
  if keyword_set(SPECIES) eq 0 then begin
    Print, 'Defaulting to SPECIES = CO2'
    Species = 'CO2'
  endif
  
  ; Determine molecular mass
  Species_options = ['CO2', 'N2O', 'CH4']
  MolecularMasses = [ 44.01, 44.013, 16.04]
  MM = MolecularMasses[where(strmatch(SPECIES_options, Species, /FOLD_CASE), species_count)]
  
  MM_ARR = fltarr(size(indata, /DIMENSIONS))
  MM_Arr[*] = mm
  
  if species_count eq 0 then begin
    MM = MolecularMasses[0]
    print, 'Using molecular mass of ' + strtrim(MM,2)
  endif
  
  ;CONVERT TO MOLECULES/CM2/S
  UnitTypes = ['molec/cm2/s','molecules/cm2/s', 'molec/cm2/sec', 'kg/m2/s', 'kg m-2 s-1']
  Key = where(strmatch(UnitTypes, Units, /FOLD_CASE))
  
  case (key) of
    
    0: begin
    ; Already in molecules/cm2/s
    ; no conversion needed
    OutData = InData
    
    end
    
    1: begin
      ; Already in molecules/cm2/s
      ; no conversion needed
      OutData = InData
      
    end
    
    2: begin
      ; Already in molecules/cm2/s
      ; no conversion needed
      OutData = InData
      
    end
    
    3: begin
      ; currently kg/m2/s
      ;kg to g  ;g to moles  ;moles to molecules ;m2 to cm2
      OutData = InData * 1000.0 / MM_arr * (6.022e23) / (100.0*100.0)
      
    end
    
    4: begin
      ; currently kg/m2/s
      ;kg to g  ;g to moles  ;moles to molecules ;m2 to cm2
      OutData = InData * 1000.0 / MM_arr * (6.022e23) / (100.0*100.0)
      
    end
    
    else: begin
      print, 'No units conversion made'
      print, 'Units (' + units + ') not recognised'
      OutData = InData
      
    end
    
  endcase
  
END